var nodemailer = require('nodemailer');
var path = require('path');
var excel = require('./excel');
var io = require('./socket');
var pool = require('./../sql/mysql');
/**
 * 获取SMTP 连接池
 * @param req
 */
function _transporter(req){

}
function sendFile(transporter,interval,req,res){
    if(!transporter){
        res.send('smtp');
        return;
    }
    var data = req.body;
    var mailOptions = {
        from: req.session.user.username+' <'+transporter.transporter.options.auth.user+'>', // sender address "Fred Foo <xxxxxxxx@qq.com>",
        to: '', // list of receivers
        subject:data.subject, // Subject line
        html: data.content // html body
    };
    var files = data.receiver.split(',');
    var len = files.length;
    var rows = [];
    for(var i=0;i<len;i++){
        var row = excel.parseExcel(path.join('./public/files/',files[i]));
        rows = rows.concat(row);
    }
    var all = rows.length;//总邮件数
    var ID = data.ID;
    var i=0;
    var socket = cur_socket(ID);
    //监听返回状态报告邮件数
    socket.on('rpt',function(rpt){
        if(all == rpt.success+rpt.fail){
            socket.emit('finish','finished');
        }
    });
    res.send('start');
    if(all>0){
        var interval = setInterval(function(){
                if(i<rows.length){
                    sendOne(transporter,mailOptions,rows[i++],socket);
                }else{
                    clearInterval(interval);
                }
            },
            interval*1000);
    }
}
exports.send = function(req,res){
    var transporter = null;
    var interval = 30;
    if(!req.session.user){res.send('nosession');return;}
    var selectSQL = 'select * from zs_mail where user_id = ?';
    pool.query(selectSQL,[req.session.user.id],function(err,info){
        if (err) {
        }else {
            var mail = info[0];
            if(mail){
                transporter  = nodemailer.createTransport({
                    host: mail.host, // 主机
                    secure: mail.secure?true:false, // 使用 SSL
                    port: mail.port, // SMTP 端口
                    auth: {
                        user: mail.user, // 账号
                        pass: mail.pass // 密码
                    }
                });
                interval = mail.intervals || interval;
            }
        }
        sendFile(transporter,interval,req,res);
    });

}
function cur_socket(ID){
	var scs = io.sockets.sockets;
	for(var i = 0;i<scs.length;i++){
		if(ID == scs[i].id){
			return scs[i];
			break;
		}
	}
	return null;
}
function sendOne(transporter,options,row,socket){
	options.subject = options.subject.replace(/#(\d+)#/g,function(){
			var args=arguments;
			return row[args[1]]||'';
		});
	options.html = options.html.replace(/#(\d+)#/g,function(){
			var args=arguments;
			return row[args[1]]||'';
		});
	options.to = row[0];
	transporter.sendMail(options, function(error, info){
		var d = new Date();
		var time = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
        time = time.replace(/\d+/g,function(){
                    var args = arguments;
                    if(args[0].length == 1){
                        return '0'+args[0];
                    }
                    return args[0];
                });
        console.error(error);
	    if(error){
	        socket.emit('fail',{time:time,to:error.response||''});
	    }else{
	        socket.emit('success',{time:time,to:info.accepted[0]});
	    }	    
	});
}